<?php
/**
 * @version Radovan Dvorsky
 * @version 20100325
 */
//require_once ('application/default/models/Db/Mapper/MapperAbstract.php');

class Db_Mapper_Harmonogram extends Db_Mapper_Abstract {
	
	/**
	 * Zisti pocet harmonogramov v db
	 * 
	 * @return int
	 */
	public function getHarmonogramsCount(){
		$select = $this->getTable()->select();
		$select->from('harmonogram',array('COUNT(hid) as count'));			
		$harmonograms = $this->getTable()->fetchAll($select);
			
		return (int)$harmonograms->current()->count;
	}
	
	public function orderHarmonograms(){
		
		$adapter = $this->getTable()->getAdapter();
		$i = 0;
		
		try{
			
			$adapter->beginTransaction();
			$select = $this->getTable()->select();
			
			$harmonogramsRowset = $this->getTable()->fetchAll();
			
			$adapter->query('UPDATE harmonogram SET ord=NULL');
			
			foreach($harmonogramsRowset as $harmonogramsRow){
				$this->getTable()->update(array(
					'ord' => $i
					),
					$adapter->quoteInto('hid = ?',$harmonogramsRow->hid)					
				);				
				$i++;
			}
			
			$cache = Zend_Registry::get('cache');
			$cache->remove('harmonograms');
			
			$adapter->commit();
			
		} catch (Zend_Exception $e){
			$adapter->rollBack();
			throw new Db_Exception($e->getMessage());
		}
	}
	
	public function changePosition($fromPostition,$toPosition){
		try{
			
			$adapter = $this->getTable()->getAdapter();
			$adapter->beginTransaction();
			/*
			 * select povodnych hodnot z db
			 */
			$srcRow = $this->getTable()->find($fromPostition)->current();
			$destRow = $this->getTable()->find($toPosition)->current();
			
			/*
			 * Nastav hotnotu NULL, kvoli UNIQUE INDEX
			 */
			$this->getTable()->update(array('ord' => NULL), $adapter->quoteInto('hid = ?',$srcRow->hid));
			
			/*
			 * Nastav nove hodnoty
			 */
			$this->getTable()->update(array('ord' => $srcRow->ord),$adapter->quoteInto('hid = ?',$destRow->hid));
			$this->getTable()->update(array('ord' => $destRow->ord),$adapter->quoteInto('hid = ?',$srcRow->hid));			
			
			$cache = Zend_Registry::get('cache');
			$cache->remove(My_Support::getCacheName('HarmonogramController','fetchAll'));			
			$adapter->commit();
		} catch(Zend_Db_Exception $e){
			$adapter->rollBack();
			throw new Db_Exception($e->getMessage());
		}		
	}
}

?>